# app.py
import os
import sqlite3
import random
import string
import datetime
from flask import Flask, render_template, request, redirect, url_for, flash, session, g, jsonify
from flask_bcrypt import Bcrypt
from functools import wraps
import openai

# 初始化Flask应用
app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)
app.config['DATABASE'] = 'car_brand_platform.db'
app.config['UPLOAD_FOLDER'] = 'static/images/car_brands'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB

# 确保上传文件夹存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

# 初始化Bcrypt
bcrypt = Bcrypt(app)

# 配置OpenAI（实际使用时请替换为您的API密钥）
openai.api_key = os.environ.get('OPENAI_API_KEY', 'your-api-key-here')

# 数据库连接函数
def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(app.config['DATABASE'])
        db.row_factory = sqlite3.Row
    return db

@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

def init_db():
    with app.app_context():
        db = get_db()
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()

# 创建数据库表结构
def create_tables():
    db = get_db()
    cursor = db.cursor()
    
    # 用户表
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT UNIQUE NOT NULL,
        email TEXT UNIQUE NOT NULL,
        password_hash TEXT NOT NULL,
        is_admin INTEGER DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
    ''')
    
    # 汽车品牌表
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS car_brands (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT UNIQUE NOT NULL,
        country TEXT NOT NULL,
        description TEXT,
        founded_year INTEGER,
        image_url TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
    ''')
    
    # 评论表
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS comments (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        car_brand_id INTEGER NOT NULL,
        user_id INTEGER NOT NULL,
        content TEXT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (car_brand_id) REFERENCES car_brands (id) ON DELETE CASCADE,
        FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
    )
    ''')
    
    # 点赞表
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS likes (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        comment_id INTEGER NOT NULL,
        user_id INTEGER NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (comment_id) REFERENCES comments (id) ON DELETE CASCADE,
        FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
        UNIQUE(comment_id, user_id)
    )
    ''')
    
    # 投票表
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS votes (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        car_brand_id INTEGER NOT NULL,
        user_id INTEGER NOT NULL,
        vote INTEGER NOT NULL, -- 1表示支持，-1表示反对
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (car_brand_id) REFERENCES car_brands (id) ON DELETE CASCADE,
        FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
        UNIQUE(car_brand_id, user_id)
    )
    ''')
    
    # 评论总结表
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS comment_summaries (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        car_brand_id INTEGER NOT NULL,
        summary TEXT NOT NULL,
        generated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (car_brand_id) REFERENCES car_brands (id) ON DELETE CASCADE,
        UNIQUE(car_brand_id)
    )
    ''')
    
    db.commit()

# 初始化默认数据（品牌+评论+用户）
def init_default_data():
    db = get_db()
    cursor = db.cursor()

    # 检查是否已有默认品牌，避免重复添加
    cursor.execute('SELECT COUNT(*) FROM car_brands')
    brand_count = cursor.fetchone()[0]
    if brand_count > 0:
        return  # 已有数据，跳过初始化

    # 添加默认汽车品牌（5个虚拟品牌）
    default_brands = [
        (
            "星驰汽车",  # 品牌名
            "中国",     # 国家
            "星驰汽车成立于2015年，专注于智能电动车型研发，以高性价比和长续航著称，主打年轻家庭用户市场。",  # 描述
            2015,       # 成立年份
            "images/car_brands/star_drive.jpg"  # 图片路径
        ),
        (
            "锋速动力",
            "德国",
            "锋速动力是德国高端性能车品牌，以极致操控和豪华内饰为核心，旗下车型多次获得国际设计大奖，主打高端商务人群。",
            1998,
            "images/car_brands/speed_force.jpg"
        ),
        (
            "绿行科技",
            "日本",
            "绿行科技专注于混动技术研发，车型以低油耗、高可靠性闻名，在全球混动市场占有率超过30%，适合城市通勤用户。",
            2005,
            "images/car_brands/green_go.jpg"
        ),
        (
            "越境汽车",
            "美国",
            "越境汽车主打全尺寸SUV和越野车型，搭载自研超强动力发动机，车身坚固耐用，是越野爱好者的首选品牌之一。",
            1982,
            "images/car_brands/cross_land.jpg"
        ),
        (
            "幻享汽车",
            "韩国",
            "幻享汽车以时尚设计和智能配置为卖点，车内搭载多屏交互系统，支持语音控制和自动驾驶辅助，深受年轻消费者喜爱。",
            2010,
            "images/car_brands/fantasy_drive.jpg"
        )
    ]

    # 插入品牌数据
    cursor.executemany('''
        INSERT INTO car_brands (name, country, description, founded_year, image_url)
        VALUES (?, ?, ?, ?, ?)
    ''', default_brands)

    # 添加默认用户（含1个管理员+2个普通用户）
    # 管理员账号：admin，密码：admin123
    admin_pwd = bcrypt.generate_password_hash("admin123").decode('utf-8')
    user1_pwd = bcrypt.generate_password_hash("user123").decode('utf-8')
    user2_pwd = bcrypt.generate_password_hash("user456").decode('utf-8')

    default_users = [
        ("admin", "admin@carplat.com", admin_pwd, 1),  # 管理员（is_admin=1）
        ("张三", "zhangsan@test.com", user1_pwd, 0),   # 普通用户1
        ("李四", "lisi@test.com", user2_pwd, 0)        # 普通用户2
    ]

    cursor.executemany('''
        INSERT INTO users (username, email, password_hash, is_admin)
        VALUES (?, ?, ?, ?)
    ''', default_users)

    # 添加默认评论（每个品牌2-3条评论）
    default_comments = [
        # 星驰汽车（品牌ID=1）
        (1, 2, "星驰的电动车续航真的不错，我买的那款冬天也能跑400多公里，家用完全够了！"),
        (1, 3, "智能系统很流畅，语音控制反应快，就是内饰材质感觉一般，希望后续能改进。"),
        (1, 2, "性价比很高，同价位里配置最全，售后服务也很及时，推荐！"),

        # 锋速动力（品牌ID=2）
        (2, 3, "操控感绝了！过弯很稳，加速也快，就是油耗有点高，毕竟是性能车可以理解。"),
        (2, 2, "内饰豪华感拉满，座椅包裹性好，长途开车不累，就是价格有点贵，适合预算充足的人。"),

        # 绿行科技（品牌ID=3）
        (3, 2, "混动技术确实牛，市区开油耗才4个多，加一次油能跑1000公里，太省心了！"),
        (3, 3, "可靠性没话说，开了3年没出过任何小毛病，就是动力偏肉，超车需要提前给油。"),

        # 越境汽车（品牌ID=4）
        (4, 3, "越野性能超强！上次去山区，烂路轻松通过，车身也很结实，安全感十足。"),
        (4, 2, "空间很大，7座布局适合大家庭，就是市区停车有点费劲，油耗也偏高。"),

        # 幻享汽车（品牌ID=5）
        (5, 2, "设计很时尚，朋友都说好看，智能配置也多，自动泊车功能对新手很友好。"),
        (5, 3, "语音控制很灵敏，能控制空调、导航这些，就是隔音效果一般，高速上有点吵。")
    ]

    cursor.executemany('''
        INSERT INTO comments (car_brand_id, user_id, content)
        VALUES (?, ?, ?)
    ''', default_comments)

    # 添加默认点赞
    default_likes = [
        (1, 3),  # 用户3给评论1点赞
        (2, 2),  # 用户2给评论2点赞
        (3, 3),  # 用户3给评论3点赞
        (4, 2),  # 用户2给评论4点赞
        (6, 3),  # 用户3给评论6点赞
        (8, 2)   # 用户2给评论8点赞
    ]

    cursor.executemany('''
        INSERT INTO likes (comment_id, user_id)
        VALUES (?, ?)
    ''', default_likes)

    # 添加默认投票
    default_votes = [
        (1, 2, 1),  # 用户2给品牌1投支持票
        (1, 3, 1),  # 用户3给品牌1投支持票
        (2, 2, 1),  # 用户2给品牌2投支持票
        (3, 3, 1),  # 用户3给品牌3投支持票
        (4, 2, 1),  # 用户2给品牌4投支持票
        (5, 3, 1),  # 用户3给品牌5投支持票
        (2, 3, -1)  # 用户3给品牌2投反对票
    ]

    cursor.executemany('''
        INSERT INTO votes (car_brand_id, user_id, vote)
        VALUES (?, ?, ?)
    ''', default_votes)

    db.commit()
    print("默认数据初始化完成！")

# 登录装饰器
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            flash('请先登录', 'warning')
            return redirect(url_for('login', next=request.url))
        return f(*args, **kwargs)
    return decorated_function

# 管理员装饰器
def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            flash('请先登录', 'warning')
            return redirect(url_for('login', next=request.url))
        
        db = get_db()
        cursor = db.cursor()
        cursor.execute('SELECT is_admin FROM users WHERE id = ?', (session['user_id'],))
        user = cursor.fetchone()
        
        if not user or user['is_admin'] != 1:
            flash('没有管理员权限', 'danger')
            return redirect(url_for('index'))
        
        return f(*args, **kwargs)
    return decorated_function

# 主页
@app.route('/')
def index():
    db = get_db()
    cursor = db.cursor()
    
    # 获取所有汽车品牌及其投票数
    cursor.execute('''
    SELECT cb.*, 
           COALESCE(SUM(v.vote), 0) as total_votes,
           (SELECT COUNT(*) FROM comments WHERE car_brand_id = cb.id) as comment_count
    FROM car_brands cb
    LEFT JOIN votes v ON cb.id = v.car_brand_id
    GROUP BY cb.id
    ORDER BY total_votes DESC
    ''')
    car_brands = cursor.fetchall()
    
    return render_template('index.html', car_brands=car_brands)

# 注册
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']
        password = request.form['password']
        confirm_password = request.form['confirm_password']
        
        if password != confirm_password:
            flash('两次密码输入不一致', 'danger')
            return redirect(url_for('register'))
        
        db = get_db()
        cursor = db.cursor()
        
        # 检查用户名是否已存在
        cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
        if cursor.fetchone():
            flash('用户名已存在', 'danger')
            return redirect(url_for('register'))
        
        # 检查邮箱是否已存在
        cursor.execute('SELECT * FROM users WHERE email = ?', (email,))
        if cursor.fetchone():
            flash('邮箱已被注册', 'danger')
            return redirect(url_for('register'))
        
        # 哈希密码
        password_hash = bcrypt.generate_password_hash(password).decode('utf-8')
        
        # 插入新用户
        cursor.execute(
            'INSERT INTO users (username, email, password_hash) VALUES (?, ?, ?)',
            (username, email, password_hash)
        )
        db.commit()
        
        flash('注册成功，请登录', 'success')
        return redirect(url_for('login'))
    
    return render_template('register.html')

# 登录
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        db = get_db()
        cursor = db.cursor()
        cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
        user = cursor.fetchone()
        
        if user and bcrypt.check_password_hash(user['password_hash'], password):
            session['user_id'] = user['id']
            session['username'] = user['username']
            session['is_admin'] = user['is_admin'] == 1
            
            next_page = request.args.get('next')
            flash('登录成功', 'success')
            return redirect(next_page or url_for('index'))
        else:
            flash('用户名或密码错误', 'danger')
            return redirect(url_for('login'))
    
    return render_template('login.html')

# 登出
@app.route('/logout')
def logout():
    session.clear()
    flash('已成功登出', 'success')
    return redirect(url_for('index'))

# 汽车品牌详情
@app.route('/brand/<int:brand_id>')
def brand_detail(brand_id):
    db = get_db()
    cursor = db.cursor()
    
    # 获取品牌信息
    cursor.execute('SELECT * FROM car_brands WHERE id = ?', (brand_id,))
    brand = cursor.fetchone()
    
    if not brand:
        flash('汽车品牌不存在', 'danger')
        return redirect(url_for('index'))
    
    # 获取投票总数
    cursor.execute('SELECT COALESCE(SUM(vote), 0) as total_votes FROM votes WHERE car_brand_id = ?', (brand_id,))
    total_votes = cursor.fetchone()['total_votes']
    
    # 获取用户是否已投票
    user_vote = None
    if 'user_id' in session:
        cursor.execute('SELECT vote FROM votes WHERE car_brand_id = ? AND user_id = ?', (brand_id, session['user_id']))
        vote_result = cursor.fetchone()
        if vote_result:
            user_vote = vote_result['vote']
    
    # 获取评论及点赞数
    cursor.execute('''
    SELECT c.*, u.username, 
           (SELECT COUNT(*) FROM likes WHERE comment_id = c.id) as like_count,
           (SELECT 1 FROM likes WHERE comment_id = c.id AND user_id = ?) as user_liked
    FROM comments c
    JOIN users u ON c.user_id = u.id
    WHERE c.car_brand_id = ?
    ORDER BY c.created_at DESC
    ''', (session['user_id'] if 'user_id' in session else -1, brand_id))
    comments = cursor.fetchall()
    
    # 获取评论总结
    cursor.execute('SELECT summary FROM comment_summaries WHERE car_brand_id = ?', (brand_id,))
    summary = cursor.fetchone()
    
    return render_template('brand_detail.html', 
                          brand=brand, 
                          total_votes=total_votes,
                          user_vote=user_vote,
                          comments=comments,
                          summary=summary)

# 添加评论
@app.route('/brand/<int:brand_id>/comment', methods=['POST'])
@login_required
def add_comment(brand_id):
    content = request.form['content'].strip()
    
    if not content:
        flash('评论内容不能为空', 'danger')
        return redirect(url_for('brand_detail', brand_id=brand_id))
    
    db = get_db()
    cursor = db.cursor()
    
    # 检查品牌是否存在
    cursor.execute('SELECT id FROM car_brands WHERE id = ?', (brand_id,))
    if not cursor.fetchone():
        flash('汽车品牌不存在', 'danger')
        return redirect(url_for('index'))
    
    # 添加评论
    cursor.execute(
        'INSERT INTO comments (car_brand_id, user_id, content) VALUES (?, ?, ?)',
        (brand_id, session['user_id'], content)
    )
    db.commit()
    
    # 评论后建议更新总结
    flash('评论成功', 'success')
    return redirect(url_for('brand_detail', brand_id=brand_id))

# 点赞评论
@app.route('/comment/<int:comment_id>/like', methods=['POST'])
@login_required
def like_comment(comment_id):
    db = get_db()
    cursor = db.cursor()
    
    # 检查评论是否存在
    cursor.execute('SELECT car_brand_id FROM comments WHERE id = ?', (comment_id,))
    comment = cursor.fetchone()
    if not comment:
        return jsonify({'status': 'error', 'message': '评论不存在'})
    
    # 检查是否已点赞
    cursor.execute('SELECT id FROM likes WHERE comment_id = ? AND user_id = ?', (comment_id, session['user_id']))
    if cursor.fetchone():
        # 取消点赞
        cursor.execute('DELETE FROM likes WHERE comment_id = ? AND user_id = ?', (comment_id, session['user_id']))
        db.commit()
        return jsonify({'status': 'success', 'action': 'unlike'})
    else:
        # 点赞
        cursor.execute('INSERT INTO likes (comment_id, user_id) VALUES (?, ?)', (comment_id, session['user_id']))
        db.commit()
        return jsonify({'status': 'success', 'action': 'like'})

# 投票
@app.route('/brand/<int:brand_id>/vote', methods=['POST'])
@login_required
def vote_brand(brand_id):
    vote = request.form.get('vote')
    if vote not in ['1', '-1']:
        flash('无效的投票', 'danger')
        return redirect(url_for('brand_detail', brand_id=brand_id))
    
    vote = int(vote)
    db = get_db()
    cursor = db.cursor()
    
    # 检查品牌是否存在
    cursor.execute('SELECT id FROM car_brands WHERE id = ?', (brand_id,))
    if not cursor.fetchone():
        flash('汽车品牌不存在', 'danger')
        return redirect(url_for('index'))
    
    # 检查是否已投票
    cursor.execute('SELECT id, vote FROM votes WHERE car_brand_id = ? AND user_id = ?', (brand_id, session['user_id']))
    existing_vote = cursor.fetchone()
    
    if existing_vote:
        if existing_vote['vote'] == vote:
            # 取消投票
            cursor.execute('DELETE FROM votes WHERE id = ?', (existing_vote['id'],))
            flash('已取消投票', 'info')
        else:
            # 更新投票
            cursor.execute('UPDATE votes SET vote = ? WHERE id = ?', (vote, existing_vote['id']))
            flash('投票已更新', 'success')
    else:
        # 新增投票
        cursor.execute('INSERT INTO votes (car_brand_id, user_id, vote) VALUES (?, ?, ?)', (brand_id, session['user_id'], vote))
        flash('投票成功', 'success')
    
    db.commit()
    return redirect(url_for('brand_detail', brand_id=brand_id))

# 生成评论总结
@app.route('/brand/<int:brand_id>/generate-summary', methods=['POST'])
@login_required
def generate_summary(brand_id):
    db = get_db()
    cursor = db.cursor()
    
    # 检查品牌是否存在
    cursor.execute('SELECT name FROM car_brands WHERE id = ?', (brand_id,))
    brand = cursor.fetchone()
    if not brand:
        flash('汽车品牌不存在', 'danger')
        return redirect(url_for('index'))
    
    # 获取该品牌的评论
    cursor.execute('SELECT content FROM comments WHERE car_brand_id = ? ORDER BY created_at DESC LIMIT 50', (brand_id,))
    comments = cursor.fetchall()
    
    if not comments:
        flash('暂无评论，无法生成总结', 'warning')
        return redirect(url_for('brand_detail', brand_id=brand_id))
    
    # 准备评论文本
    comments_text = "\n".join([f"- {comment['content']}" for comment in comments])
    
    try:
        # 调用OpenAI API生成总结
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": f"请总结以下关于{brand['name']}汽车品牌的用户评论，突出主要观点和情感倾向，保持客观中立，用中文简洁明了地表达，不超过300字。"},
                {"role": "user", "content": comments_text}
            ]
        )
        
        summary = response.choices[0].message['content'].strip()
        
        # 保存总结
        cursor.execute('''
        INSERT OR REPLACE INTO comment_summaries (car_brand_id, summary, generated_at)
        VALUES (?, ?, CURRENT_TIMESTAMP)
        ''', (brand_id, summary))
        db.commit()
        
        flash('评论总结生成成功', 'success')
    except Exception as e:
        print(f"生成总结出错: {str(e)}")
        flash('生成总结失败，请稍后再试', 'danger')
    
    return redirect(url_for('brand_detail', brand_id=brand_id))

# 管理员面板
@app.route('/admin')
@admin_required
def admin_panel():
    db = get_db()
    cursor = db.cursor()
    
    # 获取用户统计
    cursor.execute('SELECT COUNT(*) as total_users FROM users')
    total_users = cursor.fetchone()['total_users']
    
    # 获取品牌统计
    cursor.execute('SELECT COUNT(*) as total_brands FROM car_brands')
    total_brands = cursor.fetchone()['total_brands']
    
    # 获取评论统计
    cursor.execute('SELECT COUNT(*) as total_comments FROM comments')
    total_comments = cursor.fetchone()['total_comments']
    
    return render_template('admin/panel.html', 
                          total_users=total_users,
                          total_brands=total_brands,
                          total_comments=total_comments)

# 管理汽车品牌
@app.route('/admin/brands')
@admin_required
def admin_brands():
    db = get_db()
    cursor = db.cursor()
    cursor.execute('SELECT * FROM car_brands ORDER BY name')
    brands = cursor.fetchall()
    return render_template('admin/brands.html', brands=brands)

# 添加汽车品牌
@app.route('/admin/brands/add', methods=['GET', 'POST'])
@admin_required
def add_brand():
    if request.method == 'POST':
        name = request.form['name'].strip()
        country = request.form['country'].strip()
        description = request.form['description'].strip()
        founded_year = request.form['founded_year'].strip()
        
        # 处理图片上传
        image_url = None
        if 'image' in request.files and request.files['image'].filename != '':
            image = request.files['image']
            if image.filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
                # 生成随机文件名
                random_filename = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
                ext = os.path.splitext(image.filename)[1]
                filename = f"{random_filename}{ext}"
                image_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                image.save(image_path)
                image_url = f"images/car_brands/{filename}"
        
        # 验证数据
        if not name or not country:
            flash('品牌名称和国家不能为空', 'danger')
            return redirect(url_for('add_brand'))
        
        # 处理成立年份
        founded_year = int(founded_year) if founded_year.isdigit() else None
        
        db = get_db()
        cursor = db.cursor()
        
        # 检查品牌是否已存在
        cursor.execute('SELECT id FROM car_brands WHERE name = ?', (name,))
        if cursor.fetchone():
            flash('品牌已存在', 'danger')
            return redirect(url_for('add_brand'))
        
        # 添加品牌
        cursor.execute(
            '''INSERT INTO car_brands (name, country, description, founded_year, image_url) 
               VALUES (?, ?, ?, ?, ?)''',
            (name, country, description, founded_year, image_url)
        )
        db.commit()
        
        flash('品牌添加成功', 'success')
        return redirect(url_for('admin_brands'))
    
    return render_template('admin/add_brand.html')

# 编辑汽车品牌
@app.route('/admin/brands/edit/<int:brand_id>', methods=['GET', 'POST'])
@admin_required
def edit_brand(brand_id):
    db = get_db()
    cursor = db.cursor()
    
    # 获取品牌信息
    cursor.execute('SELECT * FROM car_brands WHERE id = ?', (brand_id,))
    brand = cursor.fetchone()
    
    if not brand:
        flash('品牌不存在', 'danger')
        return redirect(url_for('admin_brands'))
    
    if request.method == 'POST':
        name = request.form['name'].strip()
        country = request.form['country'].strip()
        description = request.form['description'].strip()
        founded_year = request.form['founded_year'].strip()
        
        # 处理图片上传
        image_url = brand['image_url']
        if 'image' in request.files and request.files['image'].filename != '':
            image = request.files['image']
            if image.filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
                # 删除旧图片
                if image_url:
                    old_image_path = os.path.join('static', image_url)
                    if os.path.exists(old_image_path):
                        os.remove(old_image_path)
                
                # 保存新图片
                random_filename = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
                ext = os.path.splitext(image.filename)[1]
                filename = f"{random_filename}{ext}"
                image_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                image.save(image_path)
                image_url = f"images/car_brands/{filename}"
        
        # 验证数据
        if not name or not country:
            flash('品牌名称和国家不能为空', 'danger')
            return redirect(url_for('edit_brand', brand_id=brand_id))
        
        # 处理成立年份
        founded_year = int(founded_year) if founded_year.isdigit() else None
        
        # 检查品牌名称是否已存在（排除当前品牌）
        cursor.execute('SELECT id FROM car_brands WHERE name = ? AND id != ?', (name, brand_id))
        if cursor.fetchone():
            flash('品牌名称已存在', 'danger')
            return redirect(url_for('edit_brand', brand_id=brand_id))
        
        # 更新品牌
        cursor.execute(
            '''UPDATE car_brands SET name = ?, country = ?, description = ?, 
               founded_year = ?, image_url = ?, updated_at = CURRENT_TIMESTAMP 
               WHERE id = ?''',
            (name, country, description, founded_year, image_url, brand_id)
        )
        db.commit()
        
        flash('品牌更新成功', 'success')
        return redirect(url_for('admin_brands'))
    
    return render_template('admin/edit_brand.html', brand=brand)

# 删除汽车品牌
@app.route('/admin/brands/delete/<int:brand_id>', methods=['POST'])
@admin_required
def delete_brand(brand_id):
    db = get_db()
    cursor = db.cursor()
    
    # 获取品牌信息（包括图片路径）
    cursor.execute('SELECT image_url FROM car_brands WHERE id = ?', (brand_id,))
    brand = cursor.fetchone()
    
    if not brand:
        flash('品牌不存在', 'danger')
        return redirect(url_for('admin_brands'))
    
    # 删除图片
    if brand['image_url']:
        image_path = os.path.join('static', brand['image_url'])
        if os.path.exists(image_path):
            os.remove(image_path)
    
    # 删除品牌（级联删除相关评论、投票等）
    cursor.execute('DELETE FROM car_brands WHERE id = ?', (brand_id,))
    db.commit()
    
    flash('品牌已删除', 'success')
    return redirect(url_for('admin_brands'))

# 管理用户
@app.route('/admin/users')
@admin_required
def admin_users():
    db = get_db()
    cursor = db.cursor()
    cursor.execute('SELECT * FROM users ORDER BY created_at DESC')
    users = cursor.fetchall()
    return render_template('admin/users.html', users=users)

# 删除用户
@app.route('/admin/users/delete/<int:user_id>', methods=['POST'])
@admin_required
def delete_user(user_id):
    # 不允许删除自己
    if user_id == session['user_id']:
        flash('不能删除当前登录的管理员账户', 'danger')
        return redirect(url_for('admin_users'))
    
    db = get_db()
    cursor = db.cursor()
    
    # 检查用户是否存在
    cursor.execute('SELECT id FROM users WHERE id = ?', (user_id,))
    if not cursor.fetchone():
        flash('用户不存在', 'danger')
        return redirect(url_for('admin_users'))
    
    # 删除用户
    cursor.execute('DELETE FROM users WHERE id = ?', (user_id,))
    db.commit()
    
    flash('用户已删除', 'success')
    return redirect(url_for('admin_users'))

# 管理评论
@app.route('/admin/comments')
@admin_required
def admin_comments():
    db = get_db()
    cursor = db.cursor()
    cursor.execute('''
    SELECT c.*, u.username, cb.name as brand_name 
    FROM comments c
    JOIN users u ON c.user_id = u.id
    JOIN car_brands cb ON c.car_brand_id = cb.id
    ORDER BY c.created_at DESC
    ''')
    comments = cursor.fetchall()
    return render_template('admin/comments.html', comments=comments)

# 删除评论
@app.route('/admin/comments/delete/<int:comment_id>', methods=['POST'])
@admin_required
def delete_comment(comment_id):
    db = get_db()
    cursor = db.cursor()
    
    # 获取评论所属品牌ID
    cursor.execute('SELECT car_brand_id FROM comments WHERE id = ?', (comment_id,))
    comment = cursor.fetchone()
    
    if not comment:
        flash('评论不存在', 'danger')
        return redirect(url_for('admin_comments'))
    
    # 删除评论
    cursor.execute('DELETE FROM comments WHERE id = ?', (comment_id,))
    db.commit()
    
    flash('评论已删除', 'success')
    return redirect(url_for('admin_comments'))

# 404页面
@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

# 在应用上下文中初始化数据库表和默认数据
with app.app_context():
    create_tables()
    init_default_data()  # 初始化默认数据

if __name__ == '__main__':
    app.run(debug=True)